/*
 * pps.c
 *
 *  Created on: 2014-9-26
 *      Author: Administrator
 */
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "mypps.h"
int GetPpsValue(const char* ppsDir,char* ppsAttr){
	int RetValue = 0;
	FILE *ReadFd;
	char* Index = NULL;
	unsigned char is_find = 0;
	#define MAX_CHAR	50
	char Readbuf[MAX_CHAR] = {0};
	ReadFd = fopen(ppsDir,"r");
	if (ReadFd == NULL){
		printf("Error opening pps file-%s in function %s...\n",ppsDir,__FUNCTION__);
		return 0;
	}
	while(NULL != fgets(Readbuf, MAX_CHAR, ReadFd)){
		if(strstr(Readbuf,ppsAttr) != NULL){
			is_find = 1;
			break;
		}
	}
	//printf("%s\n",Readbuf);
	if(!is_find){
		printf("Error:---Have no attr named %s in pps %s---\n",ppsAttr,ppsDir);
		return 0;
	}
	if((Index = strchr(Readbuf,':'))){
		*Index++ = '\0';
		if((Index = strchr(Index,':'))){
			*Index++ = '\0';
		}
	}
	if(Index == NULL){
		printf("Error:---Attr named %s have no value in pps %s---\n",ppsAttr,ppsDir);
		return 0;
	}
    // skip the front whitespace(include ' ', '\t', '\n')
	while ( isspace(*Index) ){
		Index++;
	}
	RetValue = atoi(Index);
	fclose(ReadFd);
	return RetValue;
}

int SetPpsValue(const char* ppsDir,char* ppsAttr,int value){
	int ppsFd;
	char wr_buf[64] = {0};
	ppsFd = open(ppsDir, O_WRONLY);
	if (ppsFd == -1) {
		printf("Unable to open %s in %s...\n", ppsDir, __FUNCTION__);
		return -1;
	}

	snprintf(wr_buf, sizeof(wr_buf), "%s:n:%d\n",ppsAttr, value);
	write(ppsFd, wr_buf, strlen(wr_buf));
	close(ppsFd);
	return 0;
}
int SetPpsValues(const char* ppsDir,char* ppsBuf){
	int ppsFd;
	ppsFd = open(ppsDir, O_WRONLY);
	if (ppsFd == -1) {
		printf("Unable to open %s in %s...\n", ppsDir, __FUNCTION__);
		return -1;
	}
	write(ppsFd, ppsBuf, strlen(ppsBuf));
	close(ppsFd);
	return 0;
}
int ppsParse(char **const optionp, char * const *tokens, char **const valuep, char **const encoding)
{
	char            *p, *p2, *attr;
	int             idx;
	const char      *token;

	p = *optionp;
	SKIPS(p);

	//
	// Collect object name
	//
	attr = p;
	if (*p == '@') {
		attr = "@";
		*valuep = ++p;
		SKIPT(p);
		if (*p)
			*p++ = '\0';

		//
		// Collect attribute
		//
	} else {
		attr = p;
		if ((p2 = strchr(p, ':'))) {
			*p2++ = '\0';
			*encoding = p = p2;
			if ((p2 = strchr(p, ':'))) {
				*p2++ = '\0';
				*valuep = p = p2;
			}
		}

		SKIPT(p);
		if (*p)
			*p++ = '\0';
	}

	//
	// Match attribute
	//
	*optionp = p;
	for (idx = 0; (token = *tokens++); idx++) {
		if (*token == *attr && strcmp(token, attr) == 0) {
			return idx;
		}
	}

	*valuep = attr;

	return -1;
}
